import axios from "axios";
import Element from "element-ui";
import router from "@/router";


axios.defaults.baseURL = "http://localhost:8081"

const request = axios.create({
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

// 请求前置拦截器
request.interceptors.request.use(
  config => {
    config.headers['Authorization'] = localStorage.getItem("token")
    return config
  })

// 请求结果拦截
request.interceptors.response.use(
  response => {
    let res = response.data
    if (res.code === 200) {
      return response
    } else {
      Element.Message.error(res.msg ? res.msg : '系统异常')
      return Promise.reject(response.data.msg)
    }
  },
  error => {
    if (error.response.data) {
      error.message = error.response.data.msg
    }
    
    if (erro.response.status === 401) {
      router.push("/login")
    }
    
    Element.Message.error(error.message, {duration: 3000})
    return Promise.reject(error.message)
  }
)

export default request